package cn.itsource.cw.service.employee;

import cn.itsource.cw.entity.TbDept;
import cn.itsource.cw.entity.TbEmployee;
import cn.itsource.cw.mapper.EmployeeMapper;
import cn.itsource.cw.service.dept.DeptServiceImpl;
import cn.itsource.cw.vo.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;

@Service
@Transactional
public class EmployeeServiceImpl {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DeptServiceImpl deptService;


    public void insertEmployee(TbEmployee employee) {
        Date now = new Date();
        //设置主键
        employee.setCreateDate(now);
        employee.setUpdateDate(now);
        employeeMapper.insertSelective(employee);
    }

    public void insertEmployeeByDeptName(TbEmployee employee, String deptName) {
        Date now = new Date();
        employee.setCreateDate(now);
        employee.setUpdateDate(now);
        TbDept dept = deptService.findDeptByName(deptName);
        employee.setDeptId(dept.getId());
        employeeMapper.insertSelective(employee);
    }

    public void updateEmployee(TbEmployee employee) {
        Date now = new Date();
        employee.setUpdateDate(now);
        employeeMapper.updateByPrimaryKeySelective(employee);
    }

    public TbEmployee findEmployeeById(String id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    public PageResult<TbEmployee> findPageByParam(TbEmployee param, int pageNum, int pageSize) {
        PageResult pageResult = new PageResult();

        Example example = new Example(TbEmployee.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(param.getGh())) {
            criteria.andEqualTo("gh", param.getGh().trim());
        }
        if (StringUtils.isNotBlank(param.getName())) {
            criteria.andLike("name", "%" + param.getName() + "%");
        }
        if (StringUtils.isNotBlank(param.getIdCard())) {
            criteria.andLike("idCard", "%" + param.getIdCard() + "%");
        }
        //todo 根据创建时间区间查询

        //分页排序
        example.orderBy("createDate").desc();
        PageHelper.startPage(pageNum, pageSize);
        PageInfo<TbEmployee> pageInfo = new PageInfo<>(employeeMapper.selectByExample(example));
        if (pageInfo.getSize() > 0) {
            pageResult.setTotalPage(pageInfo.getPages());
            pageResult.setPageNum(pageInfo.getPageNum());
            pageResult.setDataList(pageInfo.getList());
            pageResult.setTotalCount(pageInfo.getTotal());
        }
        return pageResult;
    }

}
